<?php

/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2013 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class b2c_ctl_wap_goodscollection extends wap_frontpage{

    var $noCache = true;

    public function __construct(&$app){
        parent::__construct($app);
        $shopname = app::get('wap')->getConf('wap.name');
        if(isset($shopname)){
            $this->title = app::get('b2c')->_('集货').'_'.$shopname;
            $this->keywords = app::get('b2c')->_('集货').'_'.$shopname;
            $this->description = app::get('b2c')->_('集货').'_'.$shopname;
        }
        $this->header .= '<meta name="robots" content="noindex,noarchive,nofollow" />';
        $this->_response->set_header('Cache-Control', 'no-store');
	    $this->set_tmpl('member');
	    $this->verify_member();
	    $this->pagesize = 10;
	    $this->action = $this->_request->get_act_name();
	    if(!$this->action) $this->action = 'index';
	    $this->action_view = $this->action.".html";
	    $this->member = $this->get_current_member();
        $this->objMath = kernel::single("ectools_math");

	    $this->member_status = $this->check_login();
	    if(!$this->member_status){
		    $this->pagedata['login'] = 'nologin';
	    }
    }

	/*
     *集货首页
     * */
	public function index()
	{

		$this->path[] = array('title' => app::get('b2c')->_('集货'), 'link' => $this->gen_url(array('app' => 'b2c', 'ctl' => 'wap_goodscollection', 'act' => 'index', 'full' => 1)));
		$GLOBALS['runtime']['path'] = $this->path;
		$userObject = kernel::single('b2c_user_object');
		$this->member = $userObject->get_current_member();
		$obj_business = app::get('b2c')->model('business_basicmsg');
		$obj_boo = app::get('b2c')->model('business_orders_objects');
		$db = kernel::database();
		//获取所有集货单
		$c_orders = $this->collect_order();

		foreach ($c_orders as $k => $v) {
			$res_name = $obj_business->getList('chinese_all_name,english_all_name,depot_type', array('business_id' => $v['business_id']));
			$c_orders[$k]['business_name'] = $res_name[0]['english_all_name'];
			$c_orders[$k]['depot_type'] = $res_name[0]['depot_type'];
		}

		//按仓库类型重组
		$lublino_orders = array();
		$hy_orders = array();
		$qt_orders = array();
		foreach ($c_orders as $ckey => $cvalue) {
			if ($cvalue['depot_type'] == 0) {
				$lublino_orders[] = $cvalue;
			}
			if ($cvalue['depot_type'] == 1) {
				$hy_orders[] = $cvalue;
			}
			if ($cvalue['depot_type'] == 2) {
				$qt_orders[] = $cvalue;
			}
		}

		$b_ids = $this->get_business_ids();
		$b_lublino_orders = array();
		$b_hy_orders = array();
		$b_qt_orders = array();
		foreach ($b_ids as $bkey => $bvalue) {
			foreach ($lublino_orders as $lk => $lv) {
				if ($lv['business_id'] == $bvalue) {
					$b_lublino_orders[$bvalue]['business_name'] = $lv['business_name'];
					$b_lublino_orders[$bvalue]['info'][] = $lv;
				}
			}
			foreach ($hy_orders as $hk => $hv) {
				if ($hv['business_id'] == $bvalue) {
					$b_hy_orders[$bvalue]['business_name'] = $hv['business_name'];
					$b_hy_orders[$bvalue]['info'][] = $hv;
				}
			}
			foreach ($qt_orders as $qk => $qv) {
				if ($qv['business_id'] == $bvalue) {
					$b_qt_orders[$bvalue]['business_name'] = $qv['business_name'];
					$b_qt_orders[$bvalue]['info'][] = $qv;
				}
			}
		}
		//echo '<pre>';print_r($b_qt_orders);exit;
		$gc_num = array();
		foreach ($b_lublino_orders as $bk => $bv) {

			foreach ($bv['info'] as $ik => $iv) {

				$sql = "select sum(confirm_num) as gcsum from sdb_b2c_business_orders_objects where childOrder_id={$iv['childOrder_id']}";
				$res = $db->select($sql);
				$gc_num[$bk]['sum'] = $res[0]['gcsum'];

			}
			$b_lublino_orders[$bk]['gc_sum'] = $gc_num[$bk]['sum'];
		}
		//echo '<pre>';print_r($b_lublino_orders);exit;

		$sql = "select ob.business_id,ob.goods_id,ob.mainOrder_id,depot_type,gc.status,chinese_all_name,ob.childOrder_id,brand_name,ob.bn,obj_id,has_confirm_num,gc_confirm_num,has_confirm_num as remain_num,gc_confirm_num as remain_gc_num,gc_id
		from sdb_b2c_business_orders_objects as ob
		join sdb_b2c_business_orders as bo on ob.childOrder_id = bo.childOrder_id
		join sdb_b2c_business_goodscollection as gc on ob.childOrder_id = gc.childOrder_id
		join sdb_b2c_business_basicmsg as bb on ob.business_id = bb.business_id
		join sdb_b2c_goods as g on ob.goods_id = g.goods_id
		join sdb_b2c_brand as b on g.brand_id = b.brand_id
		where ob.business_id in ('" . implode("','", $b_ids) . "') and bo.order_status<>'dead' 
		order by depot_type,bo.business_id,bo.childOrder_id,b.ordernum,b.brand_name";

		$sql2 = "select ob.business_id,sum(has_confirm_num) as total_nums
		from sdb_b2c_business_orders_objects as ob
		join sdb_b2c_business_orders as bo on ob.childOrder_id = bo.childOrder_id
		join sdb_b2c_business_goodscollection as gc on ob.childOrder_id = gc.childOrder_id
		join sdb_b2c_business_basicmsg as bb on ob.business_id = bb.business_id
		join sdb_b2c_goods as g on ob.goods_id = g.goods_id
		join sdb_b2c_brand as b on g.brand_id = b.brand_id
		where ob.business_id in ('" . implode("','", $b_ids) . "') and bo.order_status<>'dead' 
		group by ob.business_id
		order by depot_type,bo.business_id";
		//where ob.business_id in ('".implode("','",$b_ids)."') and gc.status <> '2' and ob.gc_state <> '1' and (has_confirm_num-gc_confirm_num) >0

		$data = $db->select($sql);
		$sum_collect_data = $db->select($sql2);
		$sum_business_nums = array();
		if ($data) {
			foreach ($sum_collect_data as $d){
				$sum_business_nums[$d['business_id']] = $d['total_nums'];
			}
		}

		$result = array();
		if($data) {
			foreach ($data as $v) {
				$result[$v['depot_type']][$v['business_id']]['orders'][$v['childOrder_id']][] = $v;
				$result[$v['depot_type']][$v['business_id']]['chinese_all_name'] = $v['chinese_all_name'];
				$result[$v['depot_type']][$v['business_id']]['total_nums'] = intval($sum_business_nums[$v['business_id']]);
			}
		}

		//输出
		$this->pagedata['data'] = $result;
		$this->set_tmpl('member');
		$this->page('wap/goodscollection/index.html');
	}

	//单个确认集货单商品库存
	function goCollect($id,$goods_id=null){
		$msg='参数错误';
		if(empty($_POST['con_num']))
		{
			echo json_encode(array('error'=>$msg));exit;
		}
		if(empty($_POST['mainOrder_id']))
		{
			echo json_encode(array('error'=>$msg));exit;
		}
		if(empty($_POST['gc_id']))
		{
			echo json_encode(array('error'=>$msg));exit;
		}

		$sonOrderModel = $this->app->model('business_orders_objects');
		$obj_order_items = app::get('b2c')->model('order_items');
		$cData = $sonOrderModel->getRow('*',array('obj_id'=>$id));
		$isConfirm = $sonOrderModel->update(array('gc_confirm_num'=>$_POST['con_num']),array('obj_id'=>$id));
		$res_order_item = $obj_order_items->update(array('gcnum'=>$_POST['con_num']),array('goods_id'=>$goods_id,'order_id'=>$_POST['mainOrder_id']));
		$obj_collect = $this->app->model('business_goodscollection');
		$obj_collect->update(array('member_id'=>$this->app->member_id,'status'=>'1'),array('mainOrder_id'=>$_POST['mainOrder_id']));

		if($obj_collect)
		{
			$msg = app::get('b2c')->_('操作成功');
			echo json_encode(array('success'=>$msg));exit;
		}
		else
		{
			$msg = app::get('b2c')->_('操作失败');
			echo json_encode(array('error'=>$msg));exit;
		}

	}

	//批量确认集货单商品库存
	function do_goodscollection_edit(){
		$url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'wap_goodscollection', 'act'=>'index'));

		$db = kernel::database();
		$db->beginTransaction();
		$obj_ids = $_POST['item'];
		if(!$obj_ids){
			$this->splash('failed',$url,app::get('b2c')->_('请选择商品!'),true);
		}

		$con_nums = $_POST['con_num'];
		$goods_id = $_POST['goods_id'];
		foreach($obj_ids as $key => $id){
			$sonOrderModel = $this->app->model('business_orders_objects');
			$obj_order_items = app::get('b2c')->model('order_items');
			$cData = $sonOrderModel->getRow('*',array('obj_id'=>$id));
			if($con_nums[$id] < 0){
				$this->splash('failed',$url,app::get('b2c')->_('实际集货数量不能小于0'),true);
			}
			if($con_nums[$id] > $cData['has_confirm_num']){
				$this->splash('failed',$url,app::get('b2c')->_('实际集货数量不大于计划数量'),true);
			}
			$isConfirm = $sonOrderModel->update(array('gc_confirm_num'=>$con_nums[$id]),array('obj_id'=>$id));
			$res_order_item = $obj_order_items->update(array('gcnum'=>$con_nums[$id]),array('goods_id'=>$goods_id[$id],'order_id'=>$_POST['mainOrder_id']));
		}

		if($_POST['opt'] ==''){
			$status = '1';
		}else{
			$status = '2';
		}
		$obj_collect = $this->app->model('business_goodscollection');
		$obj_collect->update(array('member_id'=>$this->app->member_id,'status'=>$status),array('mainOrder_id'=>$_POST['mainOrder_id']));
		if($status == '2'){
			foreach($obj_ids as $key => $id){
				$sonOrderModel = $this->app->model('business_orders_objects');
				$obj_goodscollection = $this->app->model('business_goodscollection');
				$obj_order_items = app::get('b2c')->model('order_items');
				$res_gc_state = $sonOrderModel->update(array('gc_state'=>'1'),array('obj_id'=>$id));
				$res_coid = $sonOrderModel->getRow('childOrder_id',array('obj_id'=>$id));
				$res_objId_all = $sonOrderModel->getList('obj_id',array('childOrder_id'=>$res_coid['childOrder_id']));
				$res_objId = $sonOrderModel->getList('obj_id',array('childOrder_id'=>$res_coid['childOrder_id'],'gc_state'=>1));

				if(count($res_objId) == count($res_objId_all)){
					$res_status = $obj_goodscollection->update(array('status'=>'2'),array('childOrder_id'=>$res_coid['childOrder_id']));
				}

				$res_gcId_all = $obj_goodscollection->getList('gc_id',array('mainOrder_id'=>$_POST['mainOrder_id']));
				$res_gcId = $obj_goodscollection->getList('gc_id',array('mainOrder_id'=>$_POST['mainOrder_id'],'status'=>'2'));

				if(count($res_gcId) == count($res_gcId_all)){

					$order = $this->app->model('orders');
					$order->update(array('c_status'=>'3'),array('order_id'=>$_POST['mainOrder_id']));
				}

			}

		}
		$db->commit();
		$this->splash('success',$url,app::get('b2c')->_('操作成功'),true);
	}

	/*
     *获取当前用户所有关联的供应商ID
     * */
	function get_business_ids(){
		$bo = app::get('b2c')->model('business_operator');
		$ids = $bo->getList('business_id',array('operator_id' => $this->app->member_id));
		$b_ids = array();
		foreach($ids as $key => $id){
			$b_ids[$key] = $id['business_id'];
		}
		return $b_ids;
	}

	//集货单(全部)
	function collect_order(){
		$b_ids = $this->get_business_ids();
		$oMsg = app::get('b2c')->model('business_goodscollection');
		//$row = $oMsg->getList('*',array('business_id|in' => $b_ids));
		$params['data'] = $oMsg->getList('*',array('business_id|in' => $b_ids));
		$result = $params['data'];
		return $result;
	}

	/*
     *本控制器公共分页函数
     * */
	function pagination($current,$totalPage,$act,$arg='',$app_id='b2c',$ctl='wap_member'){ //本控制器公共分页函数
		if (!$arg){
			$this->pagedata['pager'] = array(
				'current'=>$current,
				'total'=>$totalPage,
				'link' =>$this->gen_url(array('app'=>$app_id, 'ctl'=>$ctl,'act'=>$act,'args'=>array(($tmp = time())))),
				'token'=>$tmp,
			);
		}else{
			$arg = array_merge($arg, array(($tmp = time())));
			$this->pagedata['pager'] = array(
				'current'=>$current,
				'total'=>$totalPage,
				'link' =>$this->gen_url(array('app'=>$app_id, 'ctl'=>$ctl,'act'=>$act,'args'=>$arg)),
				'token'=>$tmp,
			);
		}
	}

	function get_start($nPage,$count){
		$maxPage = ceil($count / $this->pagesize);
		if($nPage > $maxPage) $nPage = $maxPage;
		$start = ($nPage-1) * $this->pagesize;
		$start = $start<0 ? 0 : $start;
		$aPage['start'] = $start;
		$aPage['maxPage'] = $maxPage;
		return $aPage;
	}


}

